package main

import (
	"fmt"
	"sync"
	"time"
)

// 需求: 需要统计1-400000的数字中那些是素数? for循环实现
// 结果: golang多线程需要时间6.688596287秒
var sync_1 sync.WaitGroup

var lock sync.Mutex

var count = make([]int, 0)

func prime(num int, quantity int) {
	// fmt.Println(begin, end)
	for i := (num-1)*quantity + 1; i <= num*quantity; i++ {
		if i > 1 {
			var flag = true
			for j := 2; j <= int(i/2); j++ {
				if i%j == 0 {
					flag = false
					break
				}
			}
			if flag {
				lock.Lock()
				count = append(count, i)
				lock.Unlock()
			}
		}
	}
	sync_1.Done()
}

func main() {
	start := time.Now()
	cpuNum := 10
	quantity := 40000
	for i := 1; i <= cpuNum; i++ {
		sync_1.Add(1)
		go prime(i, quantity)
	}
	sync_1.Wait()
	fmt.Printf("1-%v之间有%v个素数\n", cpuNum*quantity, len(count))
	timer := time.Since(start)
	fmt.Printf("程序执行时间: %v 秒", timer)
}
